package org.zuel.boot.demo.service.impl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.zuel.boot.demo.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SessionService {

    @Autowired
    private SysUserServiceImpl userService;

    /**
     * 验证用户会话并获取用户信息
     *
     * @param request 当前的HTTP请求
     * @return 如果用户已登录且验证通过，返回用户对象；否则返回null
     */
    public SysUser validateSession1(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("sessionId".equals(cookie.getName())) {
                    String sessionId = cookie.getValue();
                    SysUser user = userService.getSessionUser(sessionId);
                    if (user != null && isValidSession(user, sessionId)) {
                        return user;
                    }
                }
            }
        }
        return null;
    }
    public SysUser validateSession2(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("sessionId".equals(cookie.getName())) {
                    String sessionId = cookie.getValue();
                    SysUser user = userService.getSessionUser(sessionId);
                    if (user != null && isValidSession(user, sessionId)) {
                        return user;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 验证会话的有效性
     *
     * @param user 用户对象
     * @param sessionId 当前的sessionId
     * @return 如果会话有效，返回true；否则返回false
     */
    private boolean isValidSession(SysUser user, String sessionId) {
        // 示例：验证sessionId是否与用户绑定的sessionId一致
        return user.getSessionId().equals(sessionId);
    }
}